package cn.jsu.oj.dispatchServer.satellite.handler;

import cn.jsu.oj.dispatchServer.satellite.annotation.HandlerType;
import cn.jsu.oj.dispatchServer.satellite.factory.Factory;
import cn.jsu.oj.dispatchServer.satellite.handler.patrol.ServerPatrol;
import cn.jsu.oj.dispatchServer.satellite.pojo.net.ClientStatusNet;
import cn.jsu.oj.dispatchServer.satellite.pojo.net.PackNet;
import cn.jsu.oj.dispatchServer.satellite.pojo.net.RequestNet;
import cn.jsu.oj.dispatchServer.satellite.pojo.net.ResponseNet;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.FileNotFoundException;

/**
 * 侦查处理器
 *
 * @author shan
 * @date 2022/07/03
 */
@Slf4j
@Component("detectHandler")
@HandlerType(typeNo = 5)
public class DetectHandler implements Handler {

    @Autowired
    Factory handlerFactory;


    @Autowired
    ServerPatrol serverPatrol;

    /**
     * 服务器状态处理
     *
     * @param packNet net包
     */
    @Override
    public void handle(PackNet<?> packNet) throws FileNotFoundException {
        log.info("----------开始侦查......");
        RequestNet requestNet = (RequestNet) packNet.getMessage();
        String uuid = requestNet.getUuid();
        ClientStatusNet status = getClientStatus();
        log.info("----------获取成功......");
        ResponseNet responseNet = buildResponse(uuid, status);
        ((Handler) handlerFactory.getProduct((short) 4))
                .handle(new PackNet<>(packNet.getChannel()
                        , responseNet));
    }

    /**
     * 获取客户端状态
     *
     * @return {@link ClientStatusNet }
     */
    private ClientStatusNet getClientStatus() {
        return new ClientStatusNet(
                serverPatrol.detectNet(),
                serverPatrol.detectCpu(),
                serverPatrol.detectStorage(),
                serverPatrol.detectDisk(),
                serverPatrol.detectOs(),
                serverPatrol.detectSwap()
        );
    }

    /**
     * 构建响应包
     *
     * @param uuid   uuid
     * @param status 状态
     * @return {@link ResponseNet }
     */
    private ResponseNet buildResponse(String uuid, ClientStatusNet status) {
        String jsonString = JSON.toJSONString(status);
        return new ResponseNet(uuid, true, (short) 5, jsonString);
    }
}
